﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace SPSAndong.Comm
{
	public class SocClient
	{
		public class StateObject
		{
			public Socket workSocket = null;
			public const int BufferSize = 256;
			public byte[] buffer = new byte[256];
			public StringBuilder sb = new StringBuilder();
		}
		public Action<string> OnReceiveDate;
		public Action<SocClient.StateObject> OnReceive;
		private Socket soc = null;
		private int _port;
		private IPAddress _ip;
		public int Port
		{
			get
			{
				return this._port;
			}
			private set
			{
				this._port = value;
			}
		}
		public IPAddress Ip
		{
			get
			{
				return this._ip;
			}
			private set
			{
				this._ip = value;
			}
		}
		public SocClient(IPAddress ip, int nPort)
		{
			this.Port = nPort;
			this.Ip = ip;
		}
		public bool Connect()
		{
			this.soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			bool result;
			try
			{
				this.soc.Connect(new IPEndPoint(this.Ip, this.Port));
				result = true;
			}
			catch
			{
				result = false;
			}
			return result;
		}
		public void DisConnect()
		{
			bool flag = this.soc != null;
			if (flag)
			{
				this.soc.Shutdown(SocketShutdown.Both);
				this.soc.Close();
			}
		}
		public string ReceiveData()
		{
			string text = string.Empty;
			bool flag = this.soc != null && this.soc.Connected;
			if (flag)
			{
				byte[] array = new byte[1024];
				int num = this.soc.Receive(array);
				for (int i = 0; i < num; i++)
				{
					text += array[i].ToString("X2");
					Action<string> expr_5F = this.OnReceiveDate;
					if (expr_5F != null)
					{
						expr_5F.BeginInvoke(text, null, null);
					}
				}
			}
			return text;
		}
		private byte[] strToToHexByte(string hexString)
		{
			hexString = hexString.Replace(" ", "");
			bool flag = hexString.Length % 2 > 0;
			if (flag)
			{
				hexString += " ";
			}
			byte[] array = new byte[hexString.Length / 2];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);
			}
			return array;
		}
		public bool SendData(string strData)
		{
			byte[] buffer = this.strToToHexByte(strData);
			bool result;
			try
			{
				this.soc.Send(buffer);
				result = true;
				return result;
			}
			catch
			{
				this.soc.Shutdown(SocketShutdown.Both);
				this.soc.Close();
				bool flag = this.Connect();
				if (flag)
				{
					result = this.SendData(strData);
					return result;
				}
			}
			result = false;
			return result;
		}
		public bool SendData(byte[] bytes)
		{
			bool result;
			try
			{
				this.soc.Send(bytes);
				result = true;
				return result;
			}
			catch
			{
				this.soc.Shutdown(SocketShutdown.Both);
				this.soc.Close();
				bool flag = this.Connect();
				if (flag)
				{
					result = this.SendData(bytes);
					return result;
				}
			}
			result = false;
			return result;
		}
	}
}
